import axios, { AxiosResponse } from 'axios';
//  https://eudxuphalugb.sealoshzh.site 
// 创建axios实例
const request = axios.create({
  baseURL: 'https://eudxuphalugb.sealoshzh.site/api',
  timeout: 10000,
  withCredentials: true, // 重要：允许发送cookie进行身份验证
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error) => {
    // 统一错误处理
    const errorMessage = error.response?.data?.message || error.message || '请求失败';
    return Promise.reject(new Error(errorMessage));
  }
);

// API接口定义
export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
}

export interface ImageFile {
  name: string;
  path: string;
  size: string;
  mtime: string;
  isdir: boolean;
}

export interface Folder {
  name: string;
  path: string;
}

export interface PaginationInfo {
  page: number;
  per_page: number;
  total: number;
  pages: number;
}

export interface ImagesResponse {
  success: boolean;
  images: ImageFile[];
  pagination: PaginationInfo;
  message?: string;
}

export interface FoldersResponse {
  success: boolean;
  folders: Folder[];
  count: number;
  message?: string;
}

// 管理端相关接口
export interface User {
  id: number;
  username: string;
  email: string;
  is_active: boolean;
  is_superuser: boolean;
  created_at: string;
  last_login?: string;
  updated_at?: string;
}

export interface LoginResponse {
  success: boolean;
  message?: string;
  user?: User;
}

export interface CreateUserData {
  username: string;
  email: string;
  password: string;
  is_superuser: boolean;
}

export interface UpdateUserData {
  username: string;
  email: string;
  password?: string;
  is_superuser: boolean;
}

export interface UsersResponse {
  success: boolean;
  users: User[];
  pagination: PaginationInfo;
  message?: string;
}

// API方法
export const api = {
  // 自动登录
  login: (): Promise<ApiResponse> => {
    return request.post('/login');
  },

  // 获取文件夹列表
  getFolders: (): Promise<FoldersResponse> => {
    return request.get('/ftpdata-folders');
  },

  // 获取图片列表
  getImages: (folderPath: string, page: number = 1, perPage: number = 20, sortBy: string = 'time', sortOrder: string = 'desc'): Promise<ImagesResponse> => {
    return request.get('/images', {
      params: {
        path: folderPath,
        page,
        per_page: perPage,
        sort_by: sortBy,
        sort_order: sortOrder
      }
    });
  },

  // 删除图片
  deleteImage: (imagePath: string): Promise<ApiResponse> => {
    return request.post('/delete', {
      path: imagePath
    });
  },

  // 获取缩略图URL
  getThumbnailUrl: (imagePath: string, size: 'small' | 'large' = 'small'): string => {
    return `/api/thumbnail?path=${encodeURIComponent(imagePath)}&size=${size}`;
  },

  // 获取下载URL
  getDownloadUrl: (imagePath: string): string => {
    return `https://eudxuphalugb.sealoshzh.site/api/download?path=${encodeURIComponent(imagePath)}`;
  },

  // 获取二维码URL
  getQRCodeUrl: (imagePath: string, size: number = 200): string => {
    const downloadUrl = api.getDownloadUrl(imagePath);
    return `/api/qrcode?data=${encodeURIComponent(downloadUrl)}&size=${size}`;
  },

  // 文件上传
  uploadFile: (file: File, destinationPath: string, createParents: boolean = true, overwrite: boolean = false): Promise<ApiResponse> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('path', destinationPath);
    formData.append('create_parents', createParents.toString());
    formData.append('overwrite', overwrite.toString());

    return request.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 管理端API
  admin: {
    // 管理员登录
    login: (username: string, password: string): Promise<LoginResponse> => {
      return request.post('/admin/login', { username, password });
    },

    // 管理员退出
    logout: (): Promise<ApiResponse> => {
      return request.post('/admin/logout');
    },

    // 获取当前用户信息
    getCurrentUser: (): Promise<User> => {
      return request.get('/admin/current-user');
    },

    // 获取用户列表
    getUsers: (): Promise<User[]> => {
      return request.get<UsersResponse>('/admin/users').then(response => {
        return (response as any).users || [];
      });
    },

    // 创建用户
    createUser: (userData: CreateUserData): Promise<User> => {
      return request.post('/admin/users', userData);
    },

    // 更新用户
    updateUser: (userId: number, userData: UpdateUserData): Promise<User> => {
      return request.put(`/admin/users/${userId}`, userData);
    },

    // 删除用户
    deleteUser: (userId: number): Promise<ApiResponse> => {
      return request.delete(`/admin/users/${userId}`);
    },

    // 获取背景图片配置
    getBackgroundConfig: (): Promise<ApiResponse> => {
      return request.get('/admin/background-config');
    },

    // 上传背景图片
    uploadBackgroundImage: (file: File, configType: 'header' | 'background'): Promise<ApiResponse> => {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('config_type', configType);

      return request.post('/admin/background-config', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    },

    // 删除背景图片配置
    deleteBackgroundConfig: (configId: number): Promise<ApiResponse> => {
      return request.delete(`/admin/background-config/${configId}`);
    },
    
    // 重新激活背景图片配置
    activateBackgroundConfig: (configId: number): Promise<ApiResponse> => {
      return request.post(`/admin/background-config/${configId}/activate`);
    }
  },

  // 客户端获取背景配置（无需登录）
  getBackgroundConfig: (): Promise<ApiResponse> => {
    return request.get('/background-config');
  }
};

export default request;